//
//  MYYChangeInforViewController.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/10/23.
//  Copyright © 2017年 hbjApple. All rights reserved.
//资料修改

#import "MYYChangeInforViewController.h"
#import "MYYChangeInforViewCell.h"
#import "MYY_Me_Macro.h"
#import "VPImageCropperViewController.h"
#import "JXTActionSheet.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "MYYAuthenticationCell.h"
#import "UIImage+fixOrientation.h"
#import "MYYChangeInforModel.h"
#import "MYXMemberMdel.h"
#import "userinfoModel.h"
#import "MYXCoverViewController.h"
#import "MYXsignatureViewController.h"
#import "MYXAuthenticationViewController.h"
#import "MYXLabelViewController.h"
#import "MYXUpdataconfigurator.h"
#import "MYXErrorViewController.h"

#import <NIMKitMediaFetcher.h>
#import <NIMSessionInteractorImpl.h>
#import "VoteHelper.h"

#define kWith_W      80
#define ORIGINAL_MAX_WIDTH 640.0f
@interface MYYChangeInforViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,JXTActionSheetDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate,VPImageCropperDelegate,UINavigationControllerDelegate,JXTActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>{
     UITextField *birthdaytimeTF;
}
@property(nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy)  NSMutableArray *categorytitleArray;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong)NSMutableArray *titleArray;//文字数组
@property (nonatomic, strong)NSMutableArray *Array;//文字数组
@property (nonatomic, strong)  UIImageView *  _AvraImageView;
@property (nonatomic, copy) UIDatePicker *datePicker;
@property(nonatomic, strong) MYXHttpManager *MYXHttpManag;
@property(nonatomic, strong)MYYChangeInforModel *MYYChangeInforMo;
@property (nonatomic, strong)userinfoModel *userinfoMode;

@property (nonatomic, strong)MYXUpdataconfigurator *configurator;

@property (nonatomic,strong) NIMKitMediaFetcher *mediaFetcher;

@end

@implementation MYYChangeInforViewController
-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    self.MYXMemberMd = [MYXMemberMdel sharedInstance];
    [self.tableView reloadData];
}


#pragma mark - Data

- (void)loadShuJu
{
    NSArray *titleArr = @[@"家乡",
                          @"签名"];
    [self.titleArray addObjectsFromArray:titleArr];
    NSArray *titleAr = @[@"标签",
                          @"兴趣"];
    [self.Array addObjectsFromArray:titleAr];
}

-(NSMutableArray *)titleArray
{
    if (!_titleArray) {
        _titleArray =[NSMutableArray array];
    }
    return _titleArray;
}
-(NSMutableArray *)Array
{
    if (!_Array) {
        _Array =[NSMutableArray array];
    }
    return _Array;
}

- (NSMutableArray *)categorytitleArray {
    if (_categorytitleArray == nil) {
        _categorytitleArray = [NSMutableArray arrayWithObjects:@"昵称",@"生日",@"性别", nil];
    }
    return _categorytitleArray;
}


- (UIDatePicker *)datePicker
{
    if (nil == _datePicker) {
        
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.timeZone = [NSTimeZone localTimeZone];
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中
        _datePicker.locale = locale;
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.tag =500;
        [_datePicker addTarget:self action:@selector(dateChange:)forControlEvents:UIControlEventValueChanged];
    }
    
    return _datePicker;
}
//滑动
-(void)dateChange:(UIDatePicker *)pad
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy年MM月dd日";
    NSDate *endDate = [fmt dateFromString:[fmt stringFromDate:self.datePicker.date]];//[NSDate dateWithTimeIntervalSince1970:(xxx/ 1000)]
    self.userinfoMode.birthday =[NSString stringWithFormat:@"%ld",(long)[endDate timeIntervalSince1970]];
    birthdaytimeTF.text =[[fmt stringFromDate:self.datePicker.date] componentsSeparatedByString:@" " ][0];;
}

- (NSDate *)stringToDate:(NSString *)datetime formatter:(NSString*)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:format];//yyyy-MM-dd
    NSDate *date = [formatter dateFromString:datetime];
#if !__has_feature(objc_arc)
    [formatter release];
#endif
    return date;
}

-(void)setMYXMemberMd:(MYXMemberMdel *)MYXMemberMd{
    _MYXMemberMd = MYXMemberMd;
    self.userinfoMode = MYXMemberMd.userinfo;
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.MYXHttpManag =[[MYXHttpManager alloc]init];
    [self loadShuJu];
    self.edgesForExtendedLayout    = UIRectEdgeNone;
    [self createUI];
}
-(void)right
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(Submit) forControlEvents:UIControlEventTouchUpInside];
    btn.frame = CGRectMake(0, 0, 60, 44);
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    //    [self.view addSubview:btn];
    [self.navigationItem setRightBarButtonItem:cancelItem animated:NO];
    
}
-(void)Submit{
    NSLog(@"提交");
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    if (self.userinfoMode.image.length<=0) {
        self.userinfoMode.image = @"";
    }if (self.userinfoMode.username.length<=0) {
        self.userinfoMode.username = @"";
    }if (self.userinfoMode.sex.length<=0) {
        self.userinfoMode.sex = @"";
    }if (self.userinfoMode.tags.length<=0) {
        self.userinfoMode.tags = @"";
    }if (self.userinfoMode.home.length<=0) {
        self.userinfoMode.home = @"";
    }if (self.userinfoMode.birthday.length<=0) {
        self.userinfoMode.birthday = @"";
    }if (self.userinfoMode.signature.length<=0) {
        self.userinfoMode.signature = @"";
    }
    if (self.userinfoMode.image.length > 0) {
        self.userinfoMode.image = [self.userinfoMode.image componentsSeparatedByString:MYXIMGBaseUrl].lastObject;
    }
     [self updatt:self.userinfoMode.image username:@"" nickname:self.userinfoMode.username sex:self.userinfoMode.sex tags:self.userinfoMode.tags tags2:@"" age:@"" home: self.userinfoMode.home birthday:self.userinfoMode.birthday signature:self.userinfoMode.signature];
    
}
#pragma mark - UI

- (void)createUI
{
    [self right];
    self.tableView.backgroundColor = [UIColor colorWithRed:0.97f green:0.97f blue:0.97f alpha:1.00f];
    [self loadShuJu];
    [self.view addSubview:self.tableView];
}
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

#pragma mark - tableview datasource and delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==1) {
        return 3;
    }else if (section==3||section==4){
         return 1;
    }else if (section==0){
        return 0;
    }
    return 2;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==3) {
        MYYAuthenticationCell *MYYAuthenticationCe = [MYYAuthenticationCell cellWithTableView:tableView];
        
        MYYAuthenticationCe.backgroundColor =[UIColor whiteColor];
        if ([self.MYXMemberMd.is_idauth isEqualToString:@"0"]){
            MYYAuthenticationCe.contentLabel.text = @"正在审核中.....";
        }else if ([self.MYXMemberMd.is_idauth isEqualToString:@"1"]){
            MYYAuthenticationCe.contentLabel.text = @"审核通过";
        }else if([self.MYXMemberMd.is_idauth isEqualToString:@"-1"]) {
            
          MYYAuthenticationCe.contentLabel.text = @"审核失败，请重新认证";
        }
        /**<nil 没有上传实名认证  0  已上传正审核 1  审核通过  -1 审核失败  */
        
        return MYYAuthenticationCe;
    }
    MYYChangeInforViewCell *MYYChangeInforViewC = [MYYChangeInforViewCell cellWithTableView:tableView];
    MYYChangeInforViewC.backgroundColor =[UIColor whiteColor];
    if (indexPath.section==1) {
        MYYChangeInforViewC.titleLabel.text= self.categorytitleArray[indexPath.row];
        if (indexPath.row==1){
            MYYChangeInforViewC.contentLabel.hidden = YES;
            MYYChangeInforViewC.titiTextFild.hidden = NO;
            MYYChangeInforViewC.arrowImageView.hidden = YES;
            MYYChangeInforViewC.titiTextFild.placeholder = @"年-月-日";
            birthdaytimeTF = MYYChangeInforViewC.titiTextFild;
            MYYChangeInforViewC.titiTextFild.text= [MYXDateTimeHelper birthDayTimeWithIntervalString:self.userinfoMode.birthday];
            MYYChangeInforViewC.titiTextFild.inputView = self.datePicker;
        }else{
            if (indexPath.row==0) {
                 MYYChangeInforViewC.contentLabel.hidden = YES;
                 MYYChangeInforViewC.titiTextFild.hidden = NO;
                 MYYChangeInforViewC.arrowImageView.hidden = YES;
                 MYYChangeInforViewC.titiTextFild.placeholder = @"请填写昵称";
                 MYYChangeInforViewC.titiTextFild.tag = 100;
                 MYYChangeInforViewC.titiTextFild.keyboardType =UIKeyboardTypeDefault;
                 MYYChangeInforViewC.titiTextFild.text= self.userinfoMode.username;
                 MYYChangeInforViewC.titiTextFild.delegate = self;
            }else{
                MYYChangeInforViewC.contentLabel.hidden = NO;
                MYYChangeInforViewC.titiTextFild.hidden = YES;
                MYYChangeInforViewC.arrowImageView.hidden = YES;
                if ([self.userinfoMode.sex isEqualToString:@"1"]) {
                     MYYChangeInforViewC.contentLabel.text = @"男";
                }else if ([self.userinfoMode.sex isEqualToString:@"2"]){
                     MYYChangeInforViewC.contentLabel.text = @"女";
                }else{
                    MYYChangeInforViewC.contentLabel.text = @"未知";
                }
            }
        }
       
    }else if (indexPath.section==2){
        MYYChangeInforViewC.titleLabel.text= self.titleArray[indexPath.row];
        MYYChangeInforViewC.contentLabel.hidden = YES;
        MYYChangeInforViewC.titiTextFild.hidden = NO;
       
        if (indexPath.row==1){
            MYYChangeInforViewC.arrowImageView.hidden = NO;
            MYYChangeInforViewC.titiTextFild.enabled = NO;
            MYYChangeInforViewC.titiTextFild.placeholder = @"编辑个性签名";
            MYYChangeInforViewC.titiTextFild.text= self.userinfoMode.signature;
            MYYChangeInforViewC.titiTextFild.keyboardType =UIKeyboardTypeDefault;
            
        }else{
            MYYChangeInforViewC.arrowImageView.hidden = YES;
            MYYChangeInforViewC.titiTextFild.enabled = YES;
            MYYChangeInforViewC.titiTextFild.placeholder = @"请填写家乡";
            MYYChangeInforViewC.titiTextFild.text= self.userinfoMode.home;
            MYYChangeInforViewC.titiTextFild.keyboardType =UIKeyboardTypeDefault;
            MYYChangeInforViewC.titiTextFild.tag = 200;
            MYYChangeInforViewC.titiTextFild.delegate = self;
           
        }
    }else {
        MYYChangeInforViewC.titleLabel.text= self.Array[indexPath.row];
        MYYChangeInforViewC.contentLabel.hidden = YES;
        MYYChangeInforViewC.titiTextFild.hidden = NO;
        MYYChangeInforViewC.titiTextFild.enabled = NO;
        MYYChangeInforViewC.titiTextFild.placeholder = @"形容自己的词";
        MYYChangeInforViewC.titiTextFild.text= self.userinfoMode.tags;
    }
    
    return MYYChangeInforViewC;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==3) {
        return MYYMe_Resume_head_H;
    }
    return MYYMe_cert_H;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView =[[UIView alloc]init];
    headView.backgroundColor =[UIColor whiteColor];
    
    if (section==0) {
        headView.frame =CGRectMake(0, 0, WIDTH, MYYMe_Resume_head_H);
       
        self._AvraImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, (headView.frame.size.height-MYYMeImages_cell_H)/2, MYYMeImages_cell_H, MYYMeImages_cell_H)];

        if (self.MYXMemberMd.userinfo.image) {
            [self._AvraImageView sd_setImageWithURL:[NSURL URLWithString:self.MYXMemberMd.userinfo.image] placeholderImage:[UIImage imageNamed:@"AppIcon"]];
        }else{
           self._AvraImageView.image =[UIImage imageNamed:@"AppIcon"];
        }
    self._AvraImageView.contentMode = UIViewContentModeScaleAspectFill;
        self. _AvraImageView.userInteractionEnabled = YES;
        self._AvraImageView.layer.masksToBounds = YES;
        self._AvraImageView.layer.cornerRadius =MYYMeImages_cell_H/2;
        [headView addSubview:self._AvraImageView];
        
        UILabel *  _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20+self._AvraImageView.frame.size.width+5, (headView.frame.size.height-30)/2, 70, 30)];
        _titleLabel.font = MYYFont(15.0f);
        _titleLabel.numberOfLines = 1;
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.textColor = MYYColorFromRGB(0xa6a6a6);
        _titleLabel.text = @"修改头像";
        [headView addSubview:_titleLabel];
        
        UIView * _hengLine = [[UIView alloc] initWithFrame:CGRectMake(0, headView.frame.size.height-0.5, headView.frame.size.width, 0.5)];
        _hengLine.backgroundColor =MYYlineColor;
        [headView addSubview: _hengLine];
        UITapGestureRecognizer * _tap                                   = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapG:)];
        [self._AvraImageView addGestureRecognizer:_tap];
    }else{
        headView.frame =CGRectMake(0, 0, WIDTH, 0.1);
    }
    
    return headView;
}
-(CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return MYYMe_Resume_head_H;
    }
    return 0.1;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *fooerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0.1)];
   
    if (section==0) {
        fooerView.frame =CGRectMake(0, 0, WIDTH, 0.1);
        fooerView.backgroundColor =MYYlineColor;
    }else{
        fooerView.frame =CGRectMake(0, 0, WIDTH, 10);
        fooerView.backgroundColor =MYYlineColor;
    }
    
    return fooerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0||section==4) {
        return 0.1;
    }
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==1&&indexPath.row==2) {
        // 2. 添加规格控制器
//        MYXCoverViewController *_standardVC = [[MYXCoverViewController alloc] init];
//        _standardVC.types =3;
//        _standardVC.view.frame = CGRectMake(0,0, WIDTH, HEIGHT-64);
//        [UIView animateWithDuration:0.3 animations:^{
//            [_standardVC reset];
//        }];
//        _standardVC.selectgestureBlock =^(NSString * name){
//            if ([name isEqualToString:@"男"]) {
//                self.userinfoMode.sex =@"2";
//            }else if ([name isEqualToString:@"女"]){
//                self.userinfoMode.sex =@"1";
//            }
//            [self.tableView reloadData];
//
//        };
//        // 1> 添加view
//        [self.navigationController.view addSubview:_standardVC.view];
//
//        // 2> 添加控制器
//        [self.parentViewController addChildViewController:_standardVC];
    }else if (indexPath.section==2&&indexPath.row==1){
        MYXsignatureViewController *MYXsignatureVC =[[MYXsignatureViewController alloc]init];
        MYXsignatureVC.signature=self.userinfoMode.signature;
        MYXsignatureVC.placehoderString = @"填写个人签名";
        MYXsignatureVC.signatureBlock =^(NSString * signature){
            if (signature.length>0) {
                 self.userinfoMode.signature =signature;
            }
            
             [self.tableView reloadData];
         };
        MYXsignatureVC.navigationItem.title= @"个人签名";
        [self.navigationController pushViewController:MYXsignatureVC animated:YES];
     //   MYXsignatureVC.companyIntrLabel.hidden = YES;

    }else if (indexPath.section==3){
        /**<nil 没有上传实名认证  0  已上传正审核 1  审核通过  -1 审核失败  */
        if ([self.MYXMemberMd.is_idauth isEqualToString:@"0"]){
            MYXErrorViewController *MYXErrorVC =[[MYXErrorViewController alloc]init];
            MYXErrorVC.navigationItem.title= @"正在审核";
            [self.navigationController pushViewController:MYXErrorVC animated:YES];
        }else if ([self.MYXMemberMd.is_idauth isEqualToString:@"1"]){
            
        }else{
         
            MYXAuthenticationViewController *MYXAuthenticationVC =[[MYXAuthenticationViewController alloc]init];
            MYXAuthenticationVC.MYXMemberMd = self.MYXMemberMd;
            MYXAuthenticationVC.navigationItem.title= @"实名认证";
            [self.navigationController pushViewController:MYXAuthenticationVC animated:YES];
        }
       
    }else if (indexPath.section==4){
       
        MYXLabelViewController *MYXLabelViewCont =[[MYXLabelViewController alloc]init];
        MYXLabelViewCont.MYXMemberMd = self.MYXMemberMd;
        MYXLabelViewCont.LabelBlock = ^(NSString *Label) {
            self.userinfoMode.tags =Label;
           
            [self.tableView reloadData];
        };

         MYXLabelViewCont.navigationItem.title= @"我的标签";
        [self.navigationController pushViewController:MYXLabelViewCont animated:YES];
    }
}



#pragma mark -头像手势

- (void)tapG:(UITapGestureRecognizer* )gesture
{
    [self configura];
}

-(void)updatt:(NSString *)image username:(NSString *)username nickname:(NSString *)nickname sex:(NSString *)sex tags:(NSString *)tags tags2:(NSString *)tags2 age:(NSString *)age home:(NSString *)home birthday:(NSString *)birthday signature:(NSString *)signature{
    [self.MYXHttpManag useredit:image username:username nickname:nickname sex:sex tags:tags tags2:tags2 age:age home:home birthday:birthday signature:signature success:^(NSString *dataStr) {
        if ([dataStr isKindOfClass:[NSString class]]) {
            [self showTopMessage:dataStr];
        }
         [[NSNotificationCenter defaultCenter] postNotificationName:@"info" object:nil];
        [self.navigationController popViewControllerAnimated:YES];

    } failure:^(NSString *errorCode) {
        if ([errorCode isKindOfClass:[NSString class]]) {
            [self showFailureTopMessage:errorCode];
            
        }
       
    } netDown:^{
        
         [self showTopMessage:@"网络不可用"];
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag ==100) {
        if (textField.text.length>0) {
            self.userinfoMode.username =textField.text;
        }
        
       
    }else if (textField.tag ==200){
        if (textField.text.length>0) {
            self.userinfoMode.home =textField.text;
        }

        
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


#pragma mark -选择相册

-(void)configura{
//    _configurator = [[MYXUpdataconfigurator alloc] init];
//    [_configurator setup:self type:1];
    //FIXME:修改
    WS(weakSelf)
    [self.mediaFetcher fetchPhotoFromLibrary:^(NSArray *images, NSString *path, PHAssetMediaType type) {
        if (images.count > 0) {
            UIImage *image = images[0];
            weakSelf._AvraImageView.image = image;
            [[VoteHelper shared] upLoadImg:image completion:^(BOOL isSucess, NSString *msg) {
                if (isSucess) {
                     [weakSelf updatt:msg
                             username:@""
                             nickname:weakSelf.userinfoMode.username
                                  sex:weakSelf.userinfoMode.sex
                                 tags:weakSelf.userinfoMode.tags
                                tags2:@""
                                  age:@""
                                 home: weakSelf.userinfoMode.home
                             birthday:weakSelf.userinfoMode.birthday
                            signature:weakSelf.userinfoMode.signature];
                }
            }];
            
        }
      

        
    }];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NIMKitMediaFetcher *)mediaFetcher
{
    if (!_mediaFetcher) {
        _mediaFetcher = [[NIMKitMediaFetcher alloc] init];
        _mediaFetcher.limit = 1;
    }
    return _mediaFetcher;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
